/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.meteocal.utils;

import it.polimi.meteocal.entities.User;
import it.polimi.meteocal.sessionbeans.UserManager;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

@FacesConverter(value = "userConverter")
public class UserConverter implements Converter {
    
    @EJB
    UserManager um;
    
    @Override
    /* Converte la stringa selezionata dalla lista di suggerimenti in un oggetto User.
       String value è l'USERNAME dell'User */
    public Object getAsObject(FacesContext context, UIComponent component, String value){
        if (value.trim().equals("")) {  
            return null;  
        } else {  
            try {
                List<User> allUsers = um.readAllUsersFromDB();
                for (User u : allUsers) {  
                    if (u.getUsername().equals(value)) {  
                        return u;  
                    }  
                }   
            } catch(NumberFormatException exception) {  
                throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid user"));  
            }  
        }        
        return null;
    }
    
    @Override
    /* Converte gli oggetti User nella List<User> suggestions in stringhe (gli username) */
    public String getAsString(FacesContext context, UIComponent component, Object object){
        if (object == null || object.equals("")) {  
            return "";  
        } else {  
            return String.valueOf(((User) object).getUsername());  
        }  
    }
}
